<template>
    <div id="uploads">
        <div class="video-div">
            <video-player v-if="isVideoVisible" class="video-player vjs-custom-skin"
                          ref="videoPlayer"
                          :playsinline="true"
                          :options="playerOptions">
            </video-player>
            <el-upload
                    class="upload-demo"
                    action="/streetdance/file/upload"
                    :http-request="upload"
                    :limit="1"
                    :multiple="false"
                    auto-upload>
                <el-button size="small" type="primary">点击上传</el-button>
                <div class="el-upload__tip" slot="tip">    只能上传不超过500MB的视频(仅支持mp4、ogg、webm格式)  </div>
            </el-upload>
        </div>
        <div class="image-div">
            <el-image class="image-thumb" v-if="isThumbVisible" :src="videoForm.thumb" fit="contain">
                <div slot="placeholder" class="image-slot">
                    加载中<span class="dot">...</span>
                </div>
            </el-image>
            <el-upload
                    class="upload-demo"
                    action="/streetdance/file/uploadImage"
                    :limit="1"
                    :http-request="uploadImage"
                    :multiple="false"
                    auto-upload>
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
        </div>
        <div>
            <el-form :model="videoForm" status-icon :rules="videorules" ref="videoForm" label-width="100px">
                <el-form-item class="demo-passForm-item" label="视频标题" prop="title">
                    <el-input type="text" v-model="videoForm.title" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item class="demo-passForm-item" label="视频简介" prop="introduction">
                    <el-input type="textarea" v-model="videoForm.introduction" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item class="demo-passForm-item" label="视频类型">
                    <el-checkbox-group v-model="typeList" max="3">
                        <el-checkbox v-for="(item,index) in allTypeList" :key="index" :label="item.id" name="typeId">{{item.typeName}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="danger" @click="submitForm('videoForm')">发布视频</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
    import {selectAllType} from "@/api/typeFun";
    import {insertVideos} from "@/api/videoFun";
    import {Loading, Message, MessageBox} from 'element-ui';
    export default {
        name: "uploads",
        components: {},
        data(){
            return {
                allTypeList: [],
                typeList: [],//类型列表
                isThumbVisible: false,
                videoForm: {
                    title: '',//标题
                    introduction: '',//简介
                    fileId: '',//文件id
                    fileName: '',//文件名
                    fileUrl: '',//文件url地址
                    thumb: '',//文件缩略图
                },
                videorules: {
                    title: [
                        { required: true, message: '请输入视频标题', trigger: 'blur' },
                        { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
                    ],
                    introduction: [
                        { min: 0, max: 200, message: '长度不能超过 250 个字符', trigger: 'blur' }
                    ]
                },
                isVideoVisible: false,
                playerOptions: {}
            }
        },
        created(){
            selectAllType().then(res=>{
                if (res.status == 200){
                    this.allTypeList = res.data
                }
            })
        },
        mounted()
        {
        },
        methods:{
            upload(item) {
                const loading = this.$loading({
                    lock: true,
                    text: '上传中，请稍等...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                let formData = new FormData();
                formData.append("file", item.file);
                this.axios({
                    url: "/streetdance/file/upload",        // 接口
                    method: "post",
                    data: formData,
                    processData: false // 告诉axios不要去处理发送的数据(重要参数)
                }).then(res => {
                    if (res.data.status == 200) {
                        Message.error(res.data.message)
                        console.log(res.data.data.filename)
                        let title = res.data.data.filename.toString()
                        this.videoForm.title = title.substring(0, title.lastIndexOf("."))
                        this.videoForm.fileId = res.data.data.id
                        this.videoForm.fileName = res.data.data.filename
                        this.videoForm.fileUrl = res.data.data.url
                        this.isVideoVisible = true
                        setTimeout(()=>{
                            this.playerOptions = {
                                playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
                                autoplay: false, // 如果为true,浏览器准备好时开始回放。
                                muted: false, // 默认情况下将会消除任何音频。
                                loop: false, // 是否视频一结束就重新开始。
                                preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
                                language: 'zh-CN',
                                aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
                                fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
                                sources: [{
                                    type: "video/" + title.substring(title.lastIndexOf(".")+1),
                                    src: res.data.data.url // url地址
                                }],
                                poster: '', // 封面地址
                                notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
                                controlBar: {
                                    timeDivider: true, // 当前时间和持续时间的分隔符
                                    durationDisplay: true, // 显示持续时间
                                    remainingTimeDisplay: false, // 是否显示剩余时间功能
                                    fullscreenToggle: true // 是否显示全屏按钮
                                }
                            }
                        }, 100)
                    }else {
                        Message.error(res.data.message)
                    }
                    loading.close();
                })
            },
            uploadImage(item) {
                let formData = new FormData();
                formData.append("file", item.file);
                this.axios({
                    url: "/streetdance/file/uploadImage",        // 接口
                    method: "post",
                    data: formData,
                    processData: false // 告诉axios不要去处理发送的数据(重要参数)
                }).then(res => {
                    if (res.data.status == 200) {
                        this.videoForm.thumb = res.data.data.url
                        this.playerOptions.poster = res.data.data.url
                        this.isThumbVisible = true
                        Message.error(res.data.message)
                    }else {
                        Message.error(res.data.message)
                    }
                })
            },
            submitForm(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (this.videoForm.fileId === '') {
                            Message.warning("请上传视频")
                            return
                        }
                        if (this.typeList.length === 0){
                            Message.warning("请选择至少一个视频类型")
                            return
                        }
                        let typeList = []
                        this.typeList.forEach(item=>{
                            let type = {
                                id: item
                            }
                            typeList.push(type);
                        })
                        this.axios.post("/streetdance/video/insert", {
                            video: JSON.stringify(this.videoForm),
                            typeList: JSON.stringify(typeList)
                        }).then(res=>{
                            if (res.data.status == 200) {
                                Message.success(res.data.message);
                                window.location.reload();
                            }else {
                                Message.error(res.data.message);
                            }
                        })
                    } else {
                        return false;
                    }
                });
            }

        }
    }
</script>

<style scoped>
    #uploads {
        padding: 20px 20px 80px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: white;
    }
    .video-div,.image-div{
        margin: 15px;
        text-align: center;
    }
    .image-thumb {
        height: 300px;
    }
    .el-upload__tip{
        color: white;
    }
</style>
